package com.yao;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.multidex.MultiDex;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.activity.BaseActivity;
import com.base.helper.ActivityHelper;
import com.yao.helper.DialogFragmentHelper;
import com.yao.ui.IndexActivity;
import com.yao.ui.YaoWebViewActivity;
import com.yao.ui.psd.PsdGestureFragment;

import static com.yao.widget.PsdGestureView.STATE_LOGIN;
import static com.yao.widget.PsdGestureView.STATE_REGISTER;

public class BaseApplication extends Application implements ActivityHelper.OnAppListener {
    private static Context mAppContext;
    private ActivityHelper lifecycleCallbacks;

    public static BaseApplication getBaseApplication(Context context) {
        return (BaseApplication) context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();
        ARouter.init(this);
        lifecycleCallbacks = ActivityHelper.getInstance();
        lifecycleCallbacks.setOnAppListener(this);
        registerActivityLifecycleCallbacks(lifecycleCallbacks);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        if (lifecycleCallbacks != null) {
            unregisterActivityLifecycleCallbacks(lifecycleCallbacks);
            lifecycleCallbacks.setOnAppListener(null);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static Context getAppContext() {
        return mAppContext;
    }

    @Override
    public void onAppExist() {

    }

    @Override
    public void onAppBackground() {

    }

    @Override
    public void onAppForground(Activity activity) {
        if (activity instanceof IndexActivity || activity instanceof YaoWebViewActivity) {
            SharedPreferences mSharedPreference = activity.getSharedPreferences("STATE_DATA", Activity.MODE_PRIVATE);
            int state = mSharedPreference.getInt("state", STATE_REGISTER);
            if (state == STATE_LOGIN) {
                DialogFragmentHelper.showDialogFragment(((BaseActivity) activity).getSupportFragmentManager(), PsdGestureFragment.newInstance(), "PsdGesture");
            }
        }
    }
}
